package org.song.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.song.mapper.ApiMapper;
import org.song.mapper.RoleApiMapper;
import org.song.model.entity.ApiEntity;
import org.song.model.entity.RoleApiEntity;
import org.song.model.entity.RoleEntity;
import org.song.service.ApiService;
import org.song.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author song
 * @date 2022/3/10 20:22
 * 后端API处理业务类
 **/

@Slf4j
@Service(value = "backendApiServiceImpl")
public class ApiServiceImpl implements ApiService {

    @Autowired(required = true)
    @Qualifier(value = "roleServiceImpl")
    private RoleService roleService;

    @Autowired(required = true)
    @Qualifier(value = "roleApiMapper")
    private RoleApiMapper roleApiMapper;

    @Autowired(required = true)
    @Qualifier(value = "apiMapper")
    private ApiMapper apiMapper;


    @Override
    public Set<ApiEntity> getApiSetByUserName(@NonNull String username) {
        // 更具用户名查询出角色
        final Set<RoleEntity> roleSetByUserName = roleService.getRoleSetByUserName(username);
        final Set<Long> roleIdSet = roleSetByUserName.stream().map(RoleEntity::getId).collect(Collectors.toSet());
        // 根据角色id查询出API Id
        final Example roleExample = new Example(RoleEntity.class);
        roleExample.createCriteria().andIn("roleId", roleIdSet);
        final List<RoleApiEntity> roleApiEntityList = roleApiMapper.selectByExample(roleExample);
        final Set<Long> apiSet = roleApiEntityList.stream().map(RoleApiEntity::getApiId).collect(Collectors.toSet());
        final Example apiExample = new Example( ApiEntity.class );
        apiExample.createCriteria().andIn( "id" , apiSet );
        return new HashSet<>(apiMapper.selectByExample( apiExample ));
    }

}
